//
//  BIDPublishExchangeInfoViewController.m
//  HJGJCommunity
//
//  Created by mal on 2017/6/12.
//  Copyright © 2017年 mal. All rights reserved.
//

#import "BIDPublishExchangeInfoViewController.h"
#import "BIDCategoryForExchangeListViewController.h"
#import "BIDCustomTextView.h"
#import "BIDUploadFile.h"

//发布置换信息
static NSString *publishExchangeInfoURL = @"displaceAndroid/add.action";
//修改置换信息
static NSString *editURL = @"displaceAndroid/modify.action";

//分类
static NSString *categoryListURL = @"displaceTypeAndroid/list.action";

@interface BIDPublishExchangeInfoViewController ()<BIDCategoryForExchangeListViewControllerDelegate, BIDUploadFileDelegate>
{
    NSString *_selectCategoryID;
}
@end

@implementation BIDPublishExchangeInfoViewController
@synthesize categoryArr;
@synthesize goodsDic;
@synthesize isEdit;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"发布";
    _selectCategoryID = @"";
    self.maxImgCount = 9;
    if(isEdit)
    {
        self.publishRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], editURL];
    }
    else
    {
        self.publishRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], publishExchangeInfoURL];
    }
    //该方法必须调用,方法的实现在父类
    [self prepareData];
    [self prepareLayout];
    if(categoryArr && categoryArr.count>0)
    {}
    else
    {
        [self getCategoryList];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)prepareLayout
{
    _titleTF.inputAccessoryView = self.toolBar;
    _contentTextView.inputAccessoryView = self.toolBar;
    _priceTF.inputAccessoryView = self.toolBar;
    _categoryTF.inputAccessoryView = self.toolBar;
    _contentTextView.placeholder = @"描述一下你的宝贝";
    _contentTextView.placeholderColor = RGBACOLOR(191, 191, 198, 1.0);
    //
    UILabel *labelForPriceTF = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 30, 20)];
    [labelForPriceTF setTextColor:RGBACOLOR(230, 230, 237, 1.f)];
    [labelForPriceTF setText:@"元"];
    [labelForPriceTF setTextAlignment: NSTextAlignmentRight];
    [labelForPriceTF setFont:[UIFont systemFontOfSize:15.f]];
    _priceTF.rightView = labelForPriceTF;
    _priceTF.rightViewMode = UITextFieldViewModeAlways;
    //
    UILabel *labelForCategoryTF = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 30, 20)];
    [labelForCategoryTF setTextColor:RGBACOLOR(230, 230, 237, 1.f)];
    [labelForCategoryTF setText:@">"];
    [labelForCategoryTF setTextAlignment:NSTextAlignmentRight];
    [labelForCategoryTF setFont:[UIFont systemFontOfSize:15.f]];
    _categoryTF.rightView = labelForCategoryTF;
    _categoryTF.rightViewMode = UITextFieldViewModeAlways;
    //本次是修改不是新增
    if(goodsDic)
    {
        self.navigationItem.leftBarButtonItem = nil;
        _titleTF.text = goodsDic[@"title"];
        _contentTextView.text = goodsDic[@"content"];
        _categoryTF.text= goodsDic[@"typeName"];
        _selectCategoryID = goodsDic[@"typeId"];
        _priceTF.text = ANY2NSSTRING(goodsDic[@"price"]);
        NSArray *fileListArr = goodsDic[@"fileList"];
        if(fileListArr && fileListArr.count>0)
        {
            for(NSDictionary *dic in fileListArr)
            {
                NSString *strFilePath = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], dic[@"path"]];
                [_addPhotoView addPhotoWithImgURL:[NSURL URLWithString:strFilePath]];
            }
        }
    }
    else
    {
    }
}

- (void)getCategoryList
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], categoryListURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"memberId=%@", [AppDelegate getUserId]];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(id obj, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            if([obj isKindOfClass:[NSArray class]])
            {
                NSArray *arr = (NSArray *)obj;
                if(arr.count > 0)
                {
                    categoryArr = [[NSArray alloc] initWithArray:arr];
                }
            }
        }
    }];
}

/**
 显示分类

 @param sender <#sender description#>
 */
- (IBAction)categoryBtnHandler:(id)sender
{
    BIDCategoryForExchangeListViewController *vc = [[BIDCategoryForExchangeListViewController alloc] init];
    vc.delegate = self;
    vc.selectedCategoryID = _selectCategoryID;
    vc.dataSourceArr = self.categoryArr;
    [self.navigationController pushViewController:vc animated:YES];
}

/**
 发布

 @param sender <#sender description#>
 */
- (IBAction)publishBtnHandler:(id)sender
{
    NSString *strTitle = _titleTF.text;
    NSString *strContent = _contentTextView.text;
    NSString *strPrice = _priceTF.text;
    NSString *strCategory = _categoryTF.text;
    if(strTitle.length == 0)
    {
        [self showAlertView:@"标题不能为空" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        return;
    }
    if(strContent.length == 0)
    {
        [self showAlertView:@"请添加物品描述" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        return;
    }
    if(strPrice.length == 0)
    {
        [self showAlertView:@"请填写价格" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        return;
    }
    if(strCategory.length == 0)
    {
        [self showAlertView:@"请选择物品分类" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        return;
    }
    if(_addPhotoView.imgArr.count > 0)
    {
        [_uploadFile addData:@"memberId" value:[AppDelegate getUserId]];
        [_uploadFile addData:@"displace.title" value:strTitle];
        [_uploadFile addData:@"displace.typeId" value:_selectCategoryID];
        [_uploadFile addData:@"displace.content" value:strContent];
        [_uploadFile addData:@"displace.price" value:strPrice];
        if(isEdit)
        {
            //修改时需要额外传递其它参数
            [_uploadFile addData:@"displace.id" value:goodsDic[@"id"]];
            [_uploadFile addData:@"displace.states" value:goodsDic[@"states"]];
            [_uploadFile addData:@"displace.displaceVerify.id" value:goodsDic[@"displaceVerify"][@"displaceId"]];
        }
        int count = 0;
        for(UIImage *img in _addPhotoView.imgArr)
        {
            count++;
            NSString *strFileName = [[NSString alloc] initWithFormat:@"fileName%d.jpg", count];
            NSData *imgData = UIImageJPEGRepresentation(img, 0.5f);
            [_uploadFile addFileFromMemory:strFileName fieldName:@"fileUploads" data:imgData];
            [_uploadFile addData:@"fileUploadsFileName" value:strFileName];
        }
        [_uploadFile finishAddFile];
        [_uploadFile startUpload];
    }
    else
    {
        NSString *strRequestURL = @"";
        if(isEdit)
        {
            strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], editURL];
        }
        else
        {
            strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], publishExchangeInfoURL];
        }
        NSMutableString *strPost = [NSMutableString string];
        [strPost appendFormat:@"memberId=%@", [AppDelegate getUserId]];
        [strPost appendFormat:@"&displace.title=%@", strTitle];
        [strPost appendFormat:@"&displace.typeId=%@", _selectCategoryID];
        [strPost appendFormat:@"&displace.content=%@", strContent];
        [strPost appendFormat:@"&dispalce.price=%@", strPrice];
        if(isEdit)
        {
            [strPost appendFormat:@"&displace.id=%@", goodsDic[@"id"]];
            [strPost appendFormat:@"&displace.states=%@", goodsDic[@"states"]];
            [strPost appendFormat:@"&displace.displaceVerify.id=%@", goodsDic[@"displaceVerify"][@"displaceId"]];
        }
        [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
            if(errMsg)
            {
                [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
            }
            else
            {
                if(isEdit)
                {
                    [self showAlertView:@"发布成功" buttonTitle:ALERT_BTN_TITLE tag:@101 functionName:@"alertViewHandler:"];
                }
                else
                {
                    [self showAlertView:@"发布成功" buttonTitle:ALERT_BTN_TITLE tag:@100 functionName:@"alertViewHandler:"];
                }
            }
        }];
    }
}

- (void)alertViewHandler:(id)obj
{
    NSNumber *value = (NSNumber *)obj;
    if([value integerValue] == 101)
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else
    {
        [self dismissViewControllerAnimated:YES completion:^{}];
    }
}

#pragma mark - BIDUploadFileDelegate
- (void)finishUploadWithResult:(id)obj
{
    if([obj isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *dic = (NSDictionary *)obj;
        NSNumber *value = dic[@"head"][@"success"];
        if([value intValue] == 1)
        {
            if(isEdit)
            {
                [self showAlertView:@"发布成功" buttonTitle:ALERT_BTN_TITLE tag:@101 functionName:@"alertViewHandler:"];
            }
            else
            {
                [self showAlertView:@"发布成功" buttonTitle:ALERT_BTN_TITLE tag:@100 functionName:@"alertViewHandler:"];
            }
        }
        else
        {
            NSString *strErrMsg = @"";
            if(dic[@"head"][@"msg"])
            {
                strErrMsg = dic[@"head"][@"msg"];
            }
            else
            {
                strErrMsg = @"发布失败";
            }
            [self showAlertView:strErrMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
    }
}

#pragma mark - BIDCategoryForExchangeListViewControllerDelegate
- (void)getCategoryName:(NSString *)categoryName andID:(NSString *)categoryID
{
    _selectCategoryID = categoryID;
    _categoryTF.text = categoryName;
}

@end
